//
//  QRCodeScanningVC.m
//  SGQRCodeExample
//
//  Created by apple on 17/3/21.
//  Copyright © 2017年 JP_lee. All rights reserved.
//

#import "QRCodeScanningVC.h"
#import "GMStudyResModel.h"
#import "GMSignModel.h"
#import "ScanSuccessJumpVC.h"
#import "GMBuyVideoVC.h"
#import "GMPlayerViewController.h"
#import "GMReadPDFVC.h"
#import "GMCoursePackageVC.h"
#import "GMExercisesVC.h"
#import "GMExaminationVC.h"
#import "GMBuyFile.h"
#import "XZGroupIntroduceVC.h"
#import "XZMyGroupDetailVC.h"
#import "XZNewsCaseVC.h"
#import "GMSignVC.h"
#import<SystemConfiguration/CaptiveNetwork.h>
#import <AMapLocationKit/AMapLocationKit.h>

@interface QRCodeScanningVC ()<AMapLocationManagerDelegate>
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, copy) NSString *formattedAddress;
@property (nonatomic, copy) NSString *latitude;
@property (nonatomic, copy) NSString *longitude;
@end

@implementation QRCodeScanningVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // 注册观察者
    [SGQRCodeNotificationCenter addObserver:self selector:@selector(SGQRCodeInformationFromeAibum:) name:SGQRCodeInformationFromeAibum object:nil];
    [SGQRCodeNotificationCenter addObserver:self selector:@selector(SGQRCodeInformationFromeScanning:) name:SGQRCodeInformationFromeScanning object:nil];
    [self initLocation];
}
/**相册二维码扫描结果*/
- (void)SGQRCodeInformationFromeAibum:(NSNotification *)noti {
    NSString *string = noti.object;
    ScanSuccessJumpVC *jumpVC = [[ScanSuccessJumpVC alloc] init];
    jumpVC.jump_URL = string;
    [self.navigationController pushViewController:jumpVC animated:YES];
}
/**相机二维码扫描结果*/
- (void)SGQRCodeInformationFromeScanning:(NSNotification *)noti {
    SGQRCodeLog(@"noti - - %@", noti);
    NSString *string = noti.object;
    if (![string zj_isContainString:@"{#}"]) {
        //网页
        ScanSuccessJumpVC *vc = [[ScanSuccessJumpVC alloc] init];
        vc.jump_URL = string;
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    NSArray *array = [string componentsSeparatedByString:@"{#}"]; //字符串按照【分隔成数组
    if (kIsEmptyObject(array)) {
        UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"" message:@"二维码识别失败" optionStyle:OptionStyleStyleOnlyOK OkTitle:@"确定" cancelTitle:@"" okBlock:^{
            [self.navigationController popViewControllerAnimated:YES];
        } cancelBlock:^{
            
        }];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    NSString *titleStr = array[0];
    NSString *contentStr = array[1];
    if ([titleStr isEqualToString:@"RES"]) {
         //资源
        [self getRESWithID:contentStr];
    }else if ([titleStr isEqualToString:@"GROUP"]){
        //社团小组
        [self getGroupDataWithId:contentStr];
        
    }else if ([titleStr isEqualToString:@"SIGN-ENTER"]){
        //签到
        [self SignInWithID:contentStr];
        
    }else if ([titleStr isEqualToString:@"SIGN-EXIT"]){
        //签退
        [self SinExitWithID:contentStr];
    }else if ([titleStr isEqualToString:@"NEWS"]){
        //新闻资讯
        XZNewsCaseVC *news = [[XZNewsCaseVC alloc] init];
        news.newsId = contentStr;
        news.typeStr = @"1";
        [self.navigationController pushViewController:news animated:YES];
        
    }else{
        //网页
        ScanSuccessJumpVC *vc = [[ScanSuccessJumpVC alloc] init];
        vc.jump_URL = contentStr;
        [self.navigationController pushViewController:vc animated:YES];
    }
}
- (void)getRESWithID:(NSString *)resID{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@"RES" forKey:@"relType"];
    [dict setValue:resID forKey:@"relId"];

    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetScanData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyNetworkElseCache callback:^(id responseObject, NSError *error) {
      
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMStudyResModel *model = [GMStudyResModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                if (model.NormalCode >0) {
                    if (model.NormalCode ==1) {
                        UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"" message:@"关联资源已下架或不可用" optionStyle:OptionStyleStyleOnlyOK OkTitle:@"确定" cancelTitle:@"" okBlock:^{
                            [self.navigationController popViewControllerAnimated:YES];
                        } cancelBlock:^{
                            
                        }];
                        [self presentViewController:alert animated:YES completion:nil];
                    }else if (model.NormalCode ==2){
                        UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"" message:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" optionStyle:OptionStyleStyleOnlyOK OkTitle:@"确定" cancelTitle:@"" okBlock:^{
                            [self.navigationController popViewControllerAnimated:YES];
                        } cancelBlock:^{
                            
                        }];
                        [self presentViewController:alert animated:YES completion:nil];
                    }else if (model.NormalCode ==3){
                        UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"" message:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" optionStyle:OptionStyleStyleOnlyOK OkTitle:@"确定" cancelTitle:@"" okBlock:^{
                            [self.navigationController popViewControllerAnimated:YES];
                        } cancelBlock:^{
                            
                        }];
                        [self presentViewController:alert animated:YES completion:nil];
                    }
                    
                }else{
                    if ([model.ResType isEqualToNumber:@(1)]) {
                        /**视频*/
                        if (model.IsFree) {
                            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
                            play.resId = model.Id;
                            play.typeStr = @"1";
                            [self.navigationController pushViewController:play animated:YES];
                        }else{
                            GMBuyVideoVC *vc = [[GMBuyVideoVC alloc] init];
                            vc.resId = model.Id;
                            vc.ResType = model.ResType;
                         
                            vc.typeStr = @"1";
                            [self.navigationController pushViewController:vc animated:YES];
                        }
                        
                    }else if ([model.ResType isEqualToNumber:@(2)]){
                        /**文档*/
                        if (model.IsFree) {
                            GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
                            file.resId = model.Id;
                            file.typeStr = @"1";
                            [self.navigationController pushViewController:file animated:YES];
                        }else{
                            GMBuyFile *file = [[GMBuyFile alloc] init];
                          
                            file.resId = model.Id;
                            file.ResType = model.ResType;
                            file.typeStr = @"1";
                            [self.navigationController pushViewController:file animated:YES];
                        }
                        
                    }else if ([model.ResType isEqualToNumber:@(3)]){
                        /**习题*/
                        if (model.IsFree) {
                            GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
                            exercises.resId = model.Id;
                            exercises.typeStr = @"1";
                            [self.navigationController pushViewController:exercises animated:YES];
                        }else{
                            GMBuyFile *file = [[GMBuyFile alloc] init];
                          
                            file.resId = model.Id;
                            file.ResType = model.ResType;
                            file.typeStr = @"1";
                            [self.navigationController pushViewController:file animated:YES];
                        }
                        
                    }else if ([model.ResType isEqualToNumber:@(4)]){
                        /**试卷*/
                        if (model.IsFree) {
                            GMExaminationVC *exam = [[GMExaminationVC alloc] init];
                            exam.resId = model.Id;
                            exam.typeStr = @"1";
                            [self.navigationController pushViewController:exam animated:YES];
                        }else{
                            GMBuyFile *file = [[GMBuyFile alloc] init];
                        
                            file.resId = model.Id;
                            file.ResType = model.ResType;
                            file.typeStr = @"1";
                            [self.navigationController pushViewController:file animated:YES];
                        }
                        
                    }else if ([model.ResType isEqualToNumber:@(9)]){
                        /**课程包*/
                        
                        if (model.IsFree) {
                            GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
                            package.resId = model.Id;
                            package.titleStr = model.Name;
                            package.typeStr = @"1";
                            [self.navigationController pushViewController:package animated:YES];
                        }else{
                            GMBuyFile *file = [[GMBuyFile alloc] init];
                          
                            file.resId = model.Id;
                            file.ResType = model.ResType;
                            file.typeStr = @"1";
                            [self.navigationController pushViewController:file animated:YES];
                        }
                    }
                }
            }
        }
    }];
}
-(void)getGroupDataWithId:(NSString *)resID{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@"GROUP" forKey:@"relType"];
    [dict setValue:resID forKey:@"relId"];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetScanData&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyNetworkElseCache callback:^(id responseObject, NSError *error) {
        
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMStudyResModel *model = [GMStudyResModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                if (model.IsAdded) {
                    XZMyGroupDetailVC *vc = [[XZMyGroupDetailVC alloc] init];
                    vc.groupId = model.Id;
                    vc.titleStr = model.Name;
                    vc.typeStr = @"1";
                    [self.navigationController pushViewController:vc animated:YES];
                }else{
                    XZGroupIntroduceVC *vc = [[XZGroupIntroduceVC alloc] init];
                    vc.groupId = model.Id;
                    vc.titileStr = model.Name;
                    vc.typeStr= @"1";
                    [self.navigationController pushViewController:vc animated:YES];
                }
           }
        }
    }];
}
/**签到*/
- (void)SignInWithID:(NSString *)signID{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@"SIGN-ENTER" forKey:@"signFlag"];
    [dict setValue:signID forKey:@"qrcodeId"];
    [dict setValue:self.longitude forKey:@"longitude"];
    [dict setValue:self.longitude forKey:@"latitude"];
    [dict setValue:self.formattedAddress forKey:@"gpsAddress"];
    [dict setValue:[self wifiName] forKey:@"wifiName"];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostRandSignInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyNetworkElseCache callback:^(id responseObject, NSError *error) {
        
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMSignModel *model =[GMSignModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                 model.SignStatus = @"SIGN-ENTER";
                GMSignVC *vc = [[GMSignVC alloc] init];
                vc.model = model;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                NSString *msg = [responseObject objectForKey:RESULT_NAME_Message];
                UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"" message:msg optionStyle:OptionStyleStyleOnlyOK OkTitle:@"确定" cancelTitle:@"" okBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                } cancelBlock:^{
                    
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
    }];
}
/**签退*/
- (void)SinExitWithID:(NSString *)exitID{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@"SIGN-EXIT" forKey:@"signFlag"];
    [dict setValue:exitID forKey:@"qrcodeId"];
    [dict setValue:self.longitude forKey:@"longitude"];
    [dict setValue:self.longitude forKey:@"latitude"];
    [dict setValue:self.formattedAddress forKey:@"gpsAddress"];
    [dict setValue:[self wifiName] forKey:@"wifiName"];
    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=PostRandSignInfo&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyNetworkElseCache callback:^(id responseObject, NSError *error) {
        
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                GMSignModel *model =[GMSignModel mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                model.SignStatus = @"SIGN-EXIT";
                GMSignVC *vc = [[GMSignVC alloc] init];
                vc.model = model;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                NSString *msg = [responseObject objectForKey:RESULT_NAME_Message];
                UIAlertController *alert = [UIAlertController zj_alertControllerWithTitle:@"" message:msg optionStyle:OptionStyleStyleOnlyOK OkTitle:@"确定" cancelTitle:@"" okBlock:^{
                    [self.navigationController popViewControllerAnimated:YES];
                } cancelBlock:^{
                    
                }];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }
    }];
}

/**
 获取链接的wifi名称
 
 @return wifi名称
 */
- (NSString *)wifiName {
    NSArray *ifs = CFBridgingRelease(CNCopySupportedInterfaces());
    id info = nil;
    for (NSString *ifname in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((CFStringRef) ifname);
        if (info && [info count]) {
            break; }
        
    }
    NSDictionary *dic = (NSDictionary *)info;
    NSString *ssid = [[dic objectForKey:@"SSID"] lowercaseString];
    return ssid;
}
/**
 高德定位
 */
- (void)initLocation{
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.locatingWithReGeocode = YES;
    [self.locationManager startUpdatingLocation];
}
//从代理中获取经纬度跟地理信息
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode{
    self.latitude = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (reGeocode){
        self.formattedAddress =reGeocode.formattedAddress;
        NSLog(@"formattedAddress = %@",reGeocode.formattedAddress);
    }
   
}
- (void)dealloc {
    SGQRCodeLog(@"QRCodeScanningVC - dealloc");
    self.locationManager.delegate = nil;
    [self.locationManager stopUpdatingLocation];
    [SGQRCodeNotificationCenter removeObserver:self];
}

@end
